package com.tledu.controller;

import com.tledu.core.AjaxResult;
import com.tledu.dao.ProductDao;
import com.tledu.model.Employee;
import com.tledu.model.Product;
import com.tledu.service.EmployeeService;
import com.tledu.service.ProductService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("product")
@Controller
@AllArgsConstructor
public class ProductController {
    @Resource
    private ProductService productService;




    @GetMapping("/list")
    public String pro(ModelMap modelMap) {
        List<Product> productsList = productService.list();
        modelMap.addAttribute("productsList",productsList);
        return "product/product-list";
    }


    @DeleteMapping("/delete")
    @ResponseBody
    public AjaxResult<Product> delete(String id){
        int i = productService.delete(id);
        if (i != 1){
            return new AjaxResult<Product>(false,"删除失败");
        }
        return new AjaxResult<Product>(true,"删除成功");
    }


    @PostMapping("/add")
    @ResponseBody
    public AjaxResult<Product> insert(Product product){
        int i = productService.insert(product);
        System.out.println(product);
        if (i != 1){
            return new AjaxResult<Product>(false,"添加失败");
        }
        return new AjaxResult<Product>(true,"添加成功");
    }

    @GetMapping("/add")
    public String toAddJsp(){
        return "product/product-add";
    }



    @GetMapping("/edit")
    public String toEditJsp(String id,ModelMap modelMap){
        Product product= productService.selectById(id);
        modelMap.addAttribute("product",product);
        return "product/product-edit";
    }



    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult<Product> update(@RequestBody  Product product){
        System.out.println(product);
        int i = productService.update(product);

        if (i != 1){
            return new AjaxResult<Product>(false,"修改失败,不能修改编号");
        }
        return new AjaxResult<Product>(true,"修改成功");
    }



}
